import React, { Component } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { propType, filter } from 'graphql-anywhere';
import { Alert, ActivityIndicator } from 'react-native'; 
import { ListItem } from 'react-native-elements';
import { primaryColor, toast } from '../utils';

class CreditPaymentOption extends Component {
  onSelect = () => {
    if (this.props.credits>=this.props.price) {
      this.props.onSelect('credit');
    } else {
      Alert.alert(
        this.props.chinese?`对不起，您的余额不足`:`Sorry your credit is not enough`,
        this.props.chinese?`本次订单总价 $${this.props.price.toFixed(2)}`:`Order total price $${this.props.price.toFixed(2)}`,
        [
          {text: this.props.chinese?'取消':'Cancel'},
          {text: this.props.chinese?'确定':'Top Up Now', onPress: () => {
            this.props.navigation.navigate('TopUp');
          }},
        ],
        { cancelable: true }
      );
    }
  }
  componentDidMount() {
    if (this.props.price) {
      this.props.onPriceChange(this.props.price);
    }
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.price!==this.props.price) {
      this.props.onPriceChange(nextProps.price); 
    }
  }
  render() {
    const { credits, price, loading, select, chinese } = this.props;
    const disabled = price > credits;

    return (
      <ListItem leftIcon={{name:'account-balance-wallet'}} title={loading?<ActivityIndicator/>:`$${credits}`} subtitle={chinese?'KnocKnocK余额':'By KnocKnocK Credit'} onPress={loading?null:this.onSelect}
        rightIcon={!disabled?{name:select==='credit'?'radio-button-checked':'radio-button-unchecked',color:select==='credit'?primaryColor:undefined}:undefined} hideChevron={disabled}/>
    );
  }
}

export default graphql(gql`
  query CreditPaymentOption($userId:String,$type:String!,$pickup:ShippingInput,$delivery:ShippingInput,$items:[OrderItemInput],$voucherId:String,$promoCodeId:String) {
    user(id:$userId){
      id
      credit
    }
    orderPricing(type:$type,pickup:$pickup,delivery:$delivery,items:$items,voucherId:$voucherId,promoCodeId:$promoCodeId) {
      toPayPrice
    }
  }
`, {
  options: ({userId, type, items, pickupDate, deliveryDate, addressId, deliveryAddressId, voucherId,
    pickupFlexible, dropOffFlexible, express, promoCodeId}) => {
    return {
      variables: {
        userId,
        type,
        pickup: {
          date: pickupDate||deliveryDate,
          addressId,
          flexible: pickupFlexible
        },
        delivery: {
          date: deliveryDate,
          addressId: deliveryAddressId||addressId,
          flexible: dropOffFlexible,
          express
        },
        items,
        voucherId,
        promoCodeId
      }
    };
  },
  props: ({ownProps, data: {orderPricing, user, loading}}) => {
    return {
      credits: user&&user.credit,
      price: orderPricing&&orderPricing.toPayPrice,
      loading
    };
  }
})(CreditPaymentOption);
